// 游戏主类
class TankGame {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.score = 0;
        this.lives = 3;
        this.isGameRunning = false;
        this.isPaused = false;
        
        // 游戏对象
        this.playerTank = null;
        this.enemyTanks = [];
        this.bullets = [];
        this.particles = [];
        
        // 游戏设置
        this.tankSize = 40;
        this.bulletSize = 6;
        this.enemyCount = 3;
        
        // 键盘状态
        this.keys = {};
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.resetGame();
        this.gameLoop();
    }
    
    setupEventListeners() {
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            this.keys[e.key] = true;
            if (e.key === ' ') {
                e.preventDefault();
                if (this.isGameRunning && !this.isPaused) {
                    this.playerTank.shoot();
                }
            }
        });
        
        document.addEventListener('keyup', (e) => {
            this.keys[e.key] = false;
        });
        
        // 按钮事件
        document.getElementById('startBtn').addEventListener('click', () => {
            this.startGame();
        });
        
        document.getElementById('pauseBtn').addEventListener('click', () => {
            this.togglePause();
        });
    }
    
    resetGame() {
        this.score = 0;
        this.lives = 3;
        this.enemyTanks = [];
        this.bullets = [];
        this.particles = [];
        
        // 创建玩家坦克
        this.playerTank = new Tank(
            this.canvas.width / 2 - this.tankSize / 2,
            this.canvas.height - this.tankSize - 20,
            this.tankSize,
            '#3498db',
            true
        );
        
        // 创建敌方坦克
        for (let i = 0; i < this.enemyCount; i++) {
            this.createEnemyTank();
        }
        
        this.updateUI();
    }
    
    createEnemyTank() {
        const x = Math.random() * (this.canvas.width - this.tankSize);
        const y = Math.random() * 200;
        const enemy = new Tank(x, y, this.tankSize, '#e74c3c', false);
        enemy.setRandomDirection();
        this.enemyTanks.push(enemy);
    }
    
    startGame() {
        this.isGameRunning = true;
        this.isPaused = false;
        document.getElementById('startBtn').disabled = true;
        document.getElementById('pauseBtn').disabled = false;
    }
    
    togglePause() {
        if (this.isGameRunning) {
            this.isPaused = !this.isPaused;
            document.getElementById('pauseBtn').textContent = this.isPaused ? '继续' : '暂停';
        }
    }
    
    update() {
        if (!this.isGameRunning || this.isPaused) return;
        
        // 更新玩家坦克
        this.handlePlayerInput();
        this.playerTank.update(this.canvas);
        
        // 更新敌方坦克
        this.enemyTanks.forEach(enemy => {
            enemy.update(this.canvas);
            if (Math.random() < 0.01) { // 1% 概率射击
                enemy.shoot();
            }
        });
        
        // 更新子弹
        this.updateBullets();
        
        // 更新粒子效果
        this.updateParticles();
        
        // 检测碰撞
        this.checkCollisions();
        
        // 检查游戏状态
        this.checkGameStatus();
    }
    
    handlePlayerInput() {
        const speed = 3;
        
        if (this.keys['ArrowUp']) {
            this.playerTank.move(0, -speed, 0);
        }
        if (this.keys['ArrowDown']) {
            this.playerTank.move(0, speed, 180);
        }
        if (this.keys['ArrowLeft']) {
            this.playerTank.move(-speed, 0, 270);
        }
        if (this.keys['ArrowRight']) {
            this.playerTank.move(speed, 0, 90);
        }
    }
    
    updateBullets() {
        // 更新玩家子弹
        this.playerTank.bullets.forEach((bullet, index) => {
            bullet.update();
            if (bullet.isOutOfBounds(this.canvas)) {
                this.playerTank.bullets.splice(index, 1);
            }
        });
        
        // 更新敌方子弹
        this.enemyTanks.forEach(enemy => {
            enemy.bullets.forEach((bullet, index) => {
                bullet.update();
                if (bullet.isOutOfBounds(this.canvas)) {
                    enemy.bullets.splice(index, 1);
                }
            });
        });
    }
    
    updateParticles() {
        this.particles.forEach((particle, index) => {
            particle.update();
            if (particle.life <= 0) {
                this.particles.splice(index, 1);
            }
        });
    }
    
    checkCollisions() {
        // 检查玩家子弹击中敌方坦克
        this.playerTank.bullets.forEach((bullet, bulletIndex) => {
            this.enemyTanks.forEach((enemy, enemyIndex) => {
                if (this.isColliding(bullet, enemy)) {
                    // 创建爆炸效果
                    this.createExplosion(enemy.x + enemy.size/2, enemy.y + enemy.size/2);
                    
                    // 移除子弹和敌方坦克
                    this.playerTank.bullets.splice(bulletIndex, 1);
                    this.enemyTanks.splice(enemyIndex, 1);
                    
                    // 增加分数
                    this.score += 100;
                    this.updateUI();
                    
                    // 创建新的敌方坦克
                    setTimeout(() => this.createEnemyTank(), 2000);
                }
            });
        });
        
        // 检查敌方子弹击中玩家坦克
        this.enemyTanks.forEach(enemy => {
            enemy.bullets.forEach((bullet, bulletIndex) => {
                if (this.isColliding(bullet, this.playerTank)) {
                    // 创建爆炸效果
                    this.createExplosion(this.playerTank.x + this.playerTank.size/2, this.playerTank.y + this.playerTank.size/2);
                    
                    // 移除子弹
                    enemy.bullets.splice(bulletIndex, 1);
                    
                    // 减少生命值
                    this.lives--;
                    this.updateUI();
                    
                    // 重置玩家坦克位置
                    this.playerTank.x = this.canvas.width / 2 - this.tankSize / 2;
                    this.playerTank.y = this.canvas.height - this.tankSize - 20;
                }
            });
        });
    }
    
    isColliding(obj1, obj2) {
        return obj1.x < obj2.x + obj2.size &&
               obj1.x + obj1.size > obj2.x &&
               obj1.y < obj2.y + obj2.size &&
               obj1.y + obj1.size > obj2.y;
    }
    
    createExplosion(x, y) {
        for (let i = 0; i < 10; i++) {
            this.particles.push(new Particle(x, y));
        }
    }
    
    checkGameStatus() {
        if (this.lives <= 0) {
            this.gameOver();
        }
    }
    
    gameOver() {
        this.isGameRunning = false;
        alert(`游戏结束！最终得分：${this.score}`);
        document.getElementById('startBtn').disabled = false;
        document.getElementById('pauseBtn').disabled = true;
        this.resetGame();
    }
    
    updateUI() {
        document.getElementById('score').textContent = this.score;
        document.getElementById('lives').textContent = this.lives;
    }
    
    render() {
        // 清空画布
        this.ctx.fillStyle = '#27ae60';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制网格背景
        this.drawGrid();
        
        // 绘制玩家坦克
        if (this.playerTank) {
            this.playerTank.draw(this.ctx);
        }
        
        // 绘制敌方坦克
        this.enemyTanks.forEach(enemy => {
            enemy.draw(this.ctx);
        });
        
        // 绘制粒子效果
        this.particles.forEach(particle => {
            particle.draw(this.ctx);
        });
    }
    
    drawGrid() {
        this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
        this.ctx.lineWidth = 1;
        
        for (let x = 0; x <= this.canvas.width; x += 40) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.canvas.height);
            this.ctx.stroke();
        }
        
        for (let y = 0; y <= this.canvas.height; y += 40) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.canvas.width, y);
            this.ctx.stroke();
        }
    }
    
    gameLoop() {
        this.update();
        this.render();
        requestAnimationFrame(() => this.gameLoop());
    }
}

// 坦克类
class Tank {
    constructor(x, y, size, color, isPlayer) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.color = color;
        this.isPlayer = isPlayer;
        this.angle = 0;
        this.speed = 2;
        this.bullets = [];
        this.lastShot = 0;
        this.shootCooldown = 500; // 毫秒
    }
    
    move(dx, dy, angle) {
        this.x += dx;
        this.y += dy;
        this.angle = angle;
    }
    
    setRandomDirection() {
        const directions = [0, 90, 180, 270];
        this.angle = directions[Math.floor(Math.random() * directions.length)];
    }
    
    update(canvas) {
        if (!this.isPlayer) {
            // 敌方坦克AI
            this.enemyAI(canvas);
        }
        
        // 保持在画布内
        this.x = Math.max(0, Math.min(canvas.width - this.size, this.x));
        this.y = Math.max(0, Math.min(canvas.height - this.size, this.y));
    }
    
    enemyAI(canvas) {
        // 随机改变方向
        if (Math.random() < 0.02) {
            this.setRandomDirection();
        }
        
        // 根据当前方向移动
        const radians = (this.angle * Math.PI) / 180;
        const dx = Math.cos(radians) * this.speed;
        const dy = Math.sin(radians) * this.speed;
        
        this.x += dx;
        this.y += dy;
        
        // 边界检测
        if (this.x <= 0 || this.x >= canvas.width - this.size ||
            this.y <= 0 || this.y >= canvas.height - this.size) {
            this.setRandomDirection();
        }
    }
    
    shoot() {
        const now = Date.now();
        if (now - this.lastShot < this.shootCooldown) return;
        
        const bulletX = this.x + this.size / 2 - 3;
        const bulletY = this.y + this.size / 2 - 3;
        
        const bullet = new Bullet(bulletX, bulletY, this.angle, this.isPlayer);
        this.bullets.push(bullet);
        this.lastShot = now;
    }
    
    draw(ctx) {
        ctx.save();
        ctx.translate(this.x + this.size / 2, this.y + this.size / 2);
        ctx.rotate((this.angle * Math.PI) / 180);
        
        // 绘制坦克主体
        ctx.fillStyle = this.color;
        ctx.fillRect(-this.size / 2, -this.size / 2, this.size, this.size);
        
        // 绘制坦克炮管
        ctx.fillStyle = '#2c3e50';
        ctx.fillRect(0, -3, this.size / 2, 6);
        
        // 绘制坦克履带
        ctx.fillStyle = '#1a252f';
        ctx.fillRect(-this.size / 2, -this.size / 2, this.size, 8);
        ctx.fillRect(-this.size / 2, this.size / 2 - 8, this.size, 8);
        
        ctx.restore();
        
        // 绘制子弹
        this.bullets.forEach(bullet => {
            bullet.draw(ctx);
        });
    }
}

// 子弹类
class Bullet {
    constructor(x, y, angle, isPlayerBullet) {
        this.x = x;
        this.y = y;
        this.size = 6;
        this.angle = angle;
        this.speed = 8;
        this.isPlayerBullet = isPlayerBullet;
    }
    
    update() {
        const radians = (this.angle * Math.PI) / 180;
        this.x += Math.cos(radians) * this.speed;
        this.y += Math.sin(radians) * this.speed;
    }
    
    draw(ctx) {
        ctx.fillStyle = this.isPlayerBullet ? '#f39c12' : '#e67e22';
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size / 2, 0, Math.PI * 2);
        ctx.fill();
    }
    
    isOutOfBounds(canvas) {
        return this.x < 0 || this.x > canvas.width || 
               this.y < 0 || this.y > canvas.height;
    }
}

// 粒子效果类
class Particle {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.vx = (Math.random() - 0.5) * 8;
        this.vy = (Math.random() - 0.5) * 8;
        this.life = 30;
        this.maxLife = 30;
        this.size = Math.random() * 4 + 2;
    }
    
    update() {
        this.x += this.vx;
        this.y += this.vy;
        this.life--;
        this.vx *= 0.98;
        this.vy *= 0.98;
    }
    
    draw(ctx) {
        const alpha = this.life / this.maxLife;
        ctx.fillStyle = `rgba(255, 100, 0, ${alpha})`;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size * alpha, 0, Math.PI * 2);
        ctx.fill();
    }
}

// 启动游戏
window.addEventListener('load', () => {
    new TankGame();
});
